var express = require('express');
var router = express.Router();
let db = require('../tools/Db');
let to = require('../tools/to');

//获取地区数据
router.get('/areas',async(req,res,next)=>{
    let sql = "select * from e_area";
    let [err,result] = await to(db.query(sql,[]));
    if(!err){
        res.json({code:200,data:result,msg:'地区数据获取成功'});
    }else{
        next(err);
    }
})
//获取年级
router.get('/grade',async(req,res,next)=>{
    let sql = "select * from e_grade";
    let [err,result] = await to(db.query(sql,[]));
    if(!err){
        res.json({code:200,data:result,msg:'年级数据获取成功'});
    }else{
        next(err);
    }
})
//获取学科
router.get('/subject',async(req,res,next)=>{
    let sql = "select * from e_subject";
    let [err,result] = await to(db.query(sql,[]));
    if(!err){
        res.json({code:200,data:result,msg:'学科数据获取成功'});
    }else{
        next(err);
    }
})
//考试类别
router.get('/category',async(req,res,next)=>{
    let sql = "select * from e_category";
    let [err,result] = await to(db.query(sql,[]));
    if(!err){
        res.json({code:200,data:result,msg:'考试类别数据获取成功'});
    }else{
        next(err);
    }
})

//课程列表
//type:1||2  1同步，2精品
//page：页码数，默认为1
//pagesize：每一页的记录数，默认10
//totalNum：总记录数
router.get('/courses',async(req,res,next)=>{
    let {page=1,pagesize=10,type=1,area='',grade='',subject='',category=''} = req.query;

    let start = (page - 1) * pagesize;//分页公式
    let condition = '';
    if(area){
        condition += ` and area_name='${area}' `;
    }
    if(grade){
        condition += ` and grade_name='${grade}' `;
    }
    if(subject){
        condition += ` and subject_name='${subject}' `;
    }
    if(category){
        condition += ` and category_name='${category}' `;
    }

    //总记录数
    let [{totalNum}] = await db.query(`select count(id) as totalNum from e_course WHERE type=? ${condition}`,[type]);

    let sql = `SELECT id,cid,title,price,CONCAT('uploads/course/',image_src) AS image_src,type_name,area_name,subject_name FROM e_course WHERE type=? ${condition} limit ?,?`;

    let [err,result] = await to(db.query(sql,[type,start,parseInt(pagesize)]));
    // console.log(sql);
    // db.close();
    let data = {
        page:parseInt(page),
        pagesize:parseInt(pagesize),
        totalNum,
        result
    }
    
    if(!err){
        res.json({code:200,data,msg:'课程列表数据获取成功'});
    }else{
        next(err);
    }
})
module.exports = router;